using System;
using System.Collections.Generic;
using System.Data;
using MyClever.Lib;

namespace MyClever.DefaultPlugins
{
    public class Filtering : MissionPlugin
    {
        [Package(Direction.Input, "Defines which data you like to extract.")]
        enum Data2Extract { }
        
        [Package(Direction.Input, "Defines the rule-set for extracting the given data.")]
        enum ExtractRules
        {
            [Column(typeof(string), "Name of the column in which you like extract data.")]
            ColumnName,
            [Column(typeof(string), "Set the rules to extract the data. (examle: IsURL)")]
            Validation
        }

        [Package(Direction.Output, "Defines the extract of the given data.")]
        enum ExtractedData
        { }

        [Plugin(PluginDevStatus.Production, "??!!")]
        public Filtering()
        {
        }

        public override void Initialize()
        {
            //This is the first Function called by the host...
            //Put anything needed to start with here first
        }

        public override void Dispose()
        {
            //Put any cleanup code in here for when the program is stopped
        }


        protected override void Work()
        {
            MissionPluginPackage outputPackage = this.GetPackageByName(typeof(ExtractedData));
            outputPackage.CopyDataFromPackage(this.GetPackageByName(typeof(Data2Extract)));
            
            DataTableReader extractRulesPackage = this.GetDataReader(typeof(ExtractRules));
            while (extractRulesPackage.Read())
            {
                this.AddNewLoggingMessage(typeof(ExtractRules), String.Format("start extract-rule: {0}", extractRulesPackage[ExtractRules.Validation.ToString()].ToString()));

                // save all invalid rows (where the validation-test fails) first ...
                List<DataRow> invalidRows = new List<DataRow>();
                foreach (DataRow rowOn in outputPackage.Rows)
	            {
                    if (false == ValidationService.Instance.IsValid(extractRulesPackage[ExtractRules.Validation.ToString()].ToString(), rowOn[extractRulesPackage[ExtractRules.ColumnName.ToString()].ToString()].ToString()))
                    {
                        invalidRows.Add(rowOn);
                    }              		 
	            }

                // ... and delete them later.
                foreach (DataRow invalidRowOn in invalidRows)
	            {
                    outputPackage.Rows.Remove(invalidRowOn);
	            }
            }
        }
    }
}
